/**
 * @file     nextGreaterLetter.js
 * @brief    [744. 寻找比目标字母大的最小字母](https://leetcode.cn/problems/find-smallest-letter-greater-than-target/)
 * @author   Zhu
 * @date     2024-11-27 14:23
 */

/**
 * @param {character[]} letters
 * @param {character} target
 * @return {character}
 */
var nextGreatestLetter = function (letters = [], target) {
    function comp(char1 = 'a', char2 = 'b') {
        return char1.charCodeAt(0) - char2.charCodeAt(0);
    }

    const n = letters.length;
    let i = 0,
        j = n - 1,
        k = 0;
    while (i <= j) {
        const mid = (i + j) >> 1;
        const res = comp(letters[mid], target);
        if (res <= 0) {
            // letters[mid] <= target
            i = mid + 1;
            k = i;
        } else {
            j = mid - 1;
        }
    }

    return letters[k % n];
};
